package com.kexun.lds;

public class  Demo02_Tongxin {
    public static void main(String[] args) {
        Demo d = new Demo();
        new Thread (){
            @Override
            public void run() {
                while(true) {
                    try {
                        d.print1();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        new Thread (){
            @Override
            public void run() {
                while(true) {
                    try {
                        d.print2();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        new Thread (){
            @Override
            public void run() {
                while(true) {
                    try {
                        d.print3();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}
class Demo {
    //三个或三个以上的线程进行通信:
    //	使用notifyAll()方法:唤醒所有在等待的线程,且使用while进行判断
    private int flag = 1;

    public void print1() throws InterruptedException {
        //线程1
        synchronized (this) {
            while(flag != 1) {
                this.wait();
            }
            System.out.print("程");
            System.out.print("序");
            System.out.print("猿");
            System.out.print("\r\n");
            flag = 2;
//			this.notify();//只能唤醒一个在等待的线程
            this.notifyAll();//将所有等待的线程都唤醒
        }
    }
    public void print2() throws InterruptedException {
        //线程2

        synchronized (this) {
            while(flag != 2) {
                this.wait();
            }
            System.out.print("攻");
            System.out.print("城");
            System.out.print("狮");
            System.out.print("\r\n");
            flag = 3;
//			this.notify();
            this.notifyAll();//将所有等待的线程都唤醒
        }
    }



    public void print3() throws InterruptedException {
        //线程3
        synchronized (this) {
            while(flag != 3) {
                this.wait();
            }
            System.out.print("架");
            System.out.print("构");
            System.out.print("师");
            System.out.print("\r\n");
            flag = 1;
//			this.notify();
            this.notifyAll();//将所有等待的线程都唤醒
        }
    }
}